import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UsersEntity } from '../entities/user.entity';
import { ToolsService } from './tools.service';
import { LoginTdo } from '../dto/login.dto';
import { jwt } from '../../utils/jwt';
import { RedisUtilsService } from 'src/modules/redis-utils/redis-utils.service';
@Injectable()
export class LoginService {
  constructor(
    @InjectRepository(UsersEntity)
    private readonly userRepo: Repository<UsersEntity>, // private readonly toolsService: ToolsService,
    private readonly toolsService: ToolsService,
    private readonly redisUtilsService: RedisUtilsService,
  ) {}

  async login(data: LoginTdo): Promise<any | string> {
    const { username, password } = data;
    const user = await this.userRepo.findOne({ where: { username } });
    if (user && this.toolsService.checkPassword(password, user.password)) {
      // 生成token
      const token = jwt.createToken(String(user.id));
      const redisData = { token, user };
      // 放入redis缓存
      this.redisUtilsService.set(String(user.id), redisData);
      const getUser = user.toResponseObject();

      return { ...getUser, token };
      // 携带token返回
      // return user.toResponseObject(true);
    } else {
      throw new Error('账号密码错误');
    }
  }
}
